<!--
 * @Description: 填写边界和设施
 * @Author: qingyang
 * @Date: 2022-03-22 18:26:57
 * @LastEditors: qingyang
 * @LastEditTime: 2023-06-29 15:03:30
-->

<template>
  <div class="emission-list-container" :class="isReadOnly ? 'g-pt4' : ''">
    <CPageTable @register="registerPage">
      <template #headerRightButton>
        <el-button @click="handleAdd()" type="primary" v-if="!isReadOnly">
          <CIcon class="g-mr4" type="c-xian-xinjian"></CIcon>
          新增排放源
        </el-button>
      </template>
      <template #searchBarPlaceholder>共有数据 {{ totalCount }} 条</template>
      <template #sourceNameIndexSlot="{ scope }">
        <CTableColumn :main-text="scope.row.sourceName" :sub-text="getIndexPath(scope.row)">
        </CTableColumn>
      </template>
      <template #dataOriginSlot="{ scope }">
        {{ scope.row.dataOrigin ? DataOriginMap[(scope.row as IFacilityResult).dataOrigin] : '-' }}
      </template>
      <template #facilityModelSlot="{ scope }">
        <CTableColumn
          :main-text="scope.row.facilityModel"
          :sub-text="scope.row.facilityLocation"
        ></CTableColumn>
      </template>
      <template #correctionGradeSlot="{ scope }">
        {{
          scope.row.correctionGrade
            ? CorrectionGradeMap[(scope.row as IFacilityResult).correctionGrade]
            : '-'
        }}
      </template>
      <template #relationNo="{ scope }">
        <div class="g-flex-between-center">
          <div v-ellTooltip>{{ empty(scope.row.relationNo) }}</div>
          <div
            class="g-flex-start-center g-flex-shrink-0"
            v-if="scope.row.abandonedFlag || scope.row.refreshFlag"
          >
            <el-tooltip
              :content="`引用的关联关系已${scope.row.abandonedFlag ? '废弃' : '更新'}`"
              placement="top"
            >
              <CIcon
                type="c-mian-jinggao"
                class="g-flex-shrink-0 g-ml4"
                style="color: #e1b205"
              ></CIcon>
            </el-tooltip>
            <el-button v-if="!isReadOnly" text type="primary" @click="handlerThrottle(scope.row)"
              >更新</el-button
            >
          </div>
        </div>
      </template>
      <template #materialNameSlot="{ scope }">
        <CTableColumn :main-text="scope.row.materialName" :sub-text="scope.row.dataUnit">
          <template #mainTextRight>
            <div class="material-name-cell--mix" v-if="scope.row.mixedGasList?.length">
              <el-popover placement="bottom" :width="250">
                <template #reference>
                  <el-tag class="g-mr8 g-mt2" type="success">混合气体</el-tag>
                </template>
                <div v-for="item in scope.row.mixedGasList" :key="item.gas">
                  <p class="g-font-14n2"
                    >{{ item.gas }}体积占比：{{ rateToNumber(item.ratio) }}%
                  </p>
                  <p class="g-font-14n2">{{ item.gas }}摩尔质量：{{ item.molarMass }}g/mol </p>
                </div>
              </el-popover>
            </div>
          </template>
        </CTableColumn>
      </template>
      <template #op="{ scope }">
        <CTableButtonGroup :buttons-config="getTableButtonsConfig(scope.row)" />
      </template>
    </CPageTable>
    <add-info-dialog
      v-model:visible="addDialogVisible"
      :inventory-no="inventoryNo"
      :inventory-facility-no="inventoryFacilityNo"
      :data="rowData"
      :organizationCode="organizationCode"
      @refresh="refreshHandle"
      :is-read-only="isReadOnly"
    ></add-info-dialog>
  </div>
</template>
<script lang="ts">
export default {
  name: 'Emission'
};
</script>
<script lang="ts" setup>
import { defineProps, defineExpose, ref } from 'vue';
import { CPageTable, useCPageTable } from '@/components/CPageTable';
import { useList } from './useList';
import { useMessage } from '@/hooks/useMessage';
import AddInfoDialog from './components/AddInfoDialog/index.vue';
import { IFacilityResult } from '@/apis/eci/inventory/model/inventoryModel';
import { CTableColumn, CTableButtonGroup } from '@/components/CTable';
import type { TableButtonItem } from '@/components/CTable';
import { planFacilityDel, updateFacility } from '@/apis/eci/inventory/inventory';
import {
  CorrectionGradeMap,
  DataOriginMap,
  EmissionCategoryMap,
  EmissionScopeMap
} from '@/constants/enum';
import { rateToNumber, empty } from '@/utils';
import { useDebounceFn } from '@vueuse/core';

const props = defineProps({
  inventoryNo: {
    type: String,
    default: ''
  },
  organizationCode: {
    type: String,
    default: ''
  },
  isReadOnly: {
    type: Boolean,
    default: false
  }
});
const { options, totalCount } = useList(props.inventoryNo, props.isReadOnly);
const [registerPage, { refresh }] = useCPageTable(options);
const { createMessage, createConfirm } = useMessage();
const addDialogVisible = ref(false);
const inventoryFacilityNo = ref('');
const rowData = ref({});
/**
 * 配置表格的按钮
 * @param row 表格行数据
 */
function getTableButtonsConfig(row: any): TableButtonItem[] {
  return [
    {
      text: '编辑',
      // btnPermission: 'FACTOR_DETAIL',
      onClick: () => handleEdit(row)
    },
    {
      text: '删除',
      // btnPermission: 'FACTOR_DETAIL',
      onClick: () => handleDel(row)
    }
  ];
}

const handleEdit = (row: IFacilityResult) => {
  inventoryFacilityNo.value = row.inventoryFacilityNo;
  rowData.value = row;
  addDialogVisible.value = true;
};

const handleUpdate = async (row: IFacilityResult) => {
  try {
    await updateFacility(props.inventoryNo, [row.inventoryFacilityNo]);
    createMessage.success('更新排放源成功！');
    refresh();
  } catch {
    //
  }
};
const handlerThrottle = useDebounceFn(handleUpdate, 300);

const handleAdd = () => {
  inventoryFacilityNo.value = '';
  rowData.value = {};
  addDialogVisible.value = true;
};

const handleDel = (row: IFacilityResult) => {
  createConfirm('确认删除排放源？', '确认后删除该条记录！', {
    iconType: 'warning',
    confirmButtonText: '删除'
  }).then(() => {
    const params = {
      inventoryNo: props.inventoryNo,
      inventoryFacilityNo: row.inventoryFacilityNo
    };
    planFacilityDel(params).then(() => {
      createMessage.success('删除成功！');
      refresh();
    });
  });
};
const refreshHandle = () => {
  refresh();
};

function check() {
  return new Promise((resolve, reject) => {
    if (totalCount.value) {
      resolve(true);
    } else {
      createMessage.error('监测计划排放源数据不能为空！');
      reject('监测计划排放源数据不能为空！');
    }
  });
}

/**
 * 组合目录路径
 */
function getIndexPath(row: IFacilityResult) {
  return `${row.emissionScope ? EmissionScopeMap[row.emissionScope] : '-'}-${
    row.emissionCategory ? EmissionCategoryMap[row.emissionCategory] : '-'
  }-${row.ghgSourceType}`;
}

const rendertag = (row: IFacilityResult) => {
  if (row.abandonedFlag) {
    return '已废弃';
  } else {
    return '已更新';
  }
};
const renderTagColor = (row: IFacilityResult) => {
  if (row.abandonedFlag) {
    return 'danger';
  } else {
    return '';
  }
};
defineExpose({
  check
});
</script>
<style lang="scss" scoped>
.emission-list-container {
  // 虚拟滚动表格的高度
  :deep(.body-main__table) {
    // header：50px、面包屑：40px、title：56px、page-header: 56px; filter：68px; body-wrapper的padding: 32px; padding-bottom：16px
    height: calc(100vh - 50px - 40px - 56px - 56px - 68px - 32px - 16px);
    min-height: 200px;
  }
  .material-name-cell {
    width: 100%;
    &.material-name-cell--has-tag {
      :deep(.c-table-column) {
        width: calc(100% - 60px);
      }
    }

    .material-name-cell--mix {
      width: 60px;
      flex-shrink: 0;
    }
  }
}
</style>
